<template>
  <van-nav-bar title="邮箱认证" left-text="返回" left-arrow @click-left="goBack" />
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="LoginUser.email"
        name="email"
        label="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
      <van-field
        v-model="code"
        name="code"
        center
        clearable
        label="邮箱验证码"
        placeholder="请输入邮箱验证码"
        :rules="[{ required: true, message: '请填写邮箱验证码' }]"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            :disabled="disabled"
            @click="ChangeCount"
          >
            <van-count-down
              v-show="disabled"
              ref="countDown"
              :time="120000"
              :auto-start="false"
              :format="format"
              @finish="onFinish"
            />
            <span v-if="!disabled">发送验证码</span>
          </van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 提交 </van-button>
    </div>
  </van-form>
</template>
<script setup>
const { cookies } = useCookies();
const router = useRouter();
const LoginUser = reactive(cookies.get("LoginUser"));
const disabled = ref(false);
const format = ref("ss秒");
const code = ref(null);
const countDown = ref(null);
const goBack = () => {
  router.push("/business/base/index");
};
// 发送验证码
const ChangeCount = async () => {
  disabled.value = true;
  // 倒计时开始
  countDown.value.start();
  let result = await Api.emailcode({ email: LoginUser.email, busid: LoginUser.id });
  if (result.code == 1) {
    showNotify({
      type: "success",
      message: result.msg,
    });
  } else {
    showNotify({ type: "danger", message: result.msg });
  }
};

// 倒计时结束触发
const onFinish = () => {
  disabled.value = false;
  countDown.value.reset();
};

const onSubmit = async (val) => {
  let data = {
    email: val.email,
    code: val.code,
    busid: LoginUser.id,
  };
  let result = await Api.attestation(data);
  if (result.code == 1) {
    showNotify({
      type: "success",
      message: result.msg,
      onClose: () => {
        router.push("/business/base/index");
      },
    });
  } else {
    showNotify({ type: "danger", message: result.msg });
  }
};
</script>
